﻿using System;
using System.Linq;
using System.Xml.Linq;

namespace OneBusAway.Util
{
    public static class XmlHelper
    {
        public static T Create<T>(XElement rootElement)
            where T : class, new()
        {
            T model = new T();
            XmlHelper.Fill(model, rootElement);
            return model;
        }

        public static void Fill<T>(T objectModel, XElement rootElement)
            where T : class
        {
            if (objectModel == null)
                throw new ArgumentNullException("objectModel");

            if (rootElement == null)
                throw new ArgumentNullException("rootElement");

            var props = objectModel.GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
            foreach (var prop in props)
            {
                var fromXml = prop.GetCustomAttributes(typeof(FromXmlAttribute), true).FirstOrDefault() as FromXmlAttribute;
                if (fromXml != null)
                {
                    var element = rootElement.Element(fromXml.ElementName);
                    if (element != null) {

                        object value = element.Value;

                        if (!string.IsNullOrEmpty(fromXml.Converter))
                        {
                            var converter = objectModel.GetType().GetMethod(fromXml.Converter);
                            if (converter != null)
                            {
                                value = converter.Invoke(objectModel, new object[] { value });
                            }
                        }

                        prop.SetValue(objectModel, value, null);
                    }
                }
            }
        }
    }
}
